package com.bc.trade.util;

import java.io.FileInputStream;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.interfaces.RSAPrivateKey;
import java.util.Enumeration;
import java.util.HashMap;

import javax.crypto.Cipher;

import org.apache.log4j.Logger;

public class Rsa {
	private static Logger logger = Logger.getLogger(Rsa.class.getName());
	private static final String ENCODING = "UTF-8";
	private static HashMap<String,PrivateKey> privateKeys = new HashMap<String,PrivateKey>();
	
	public static String decrypt(String data, String pfx_path, String pfx_pass) throws Exception {

		try {

			RSAPrivateKey pbk = getPrivateKey(pfx_path, pfx_pass);

			//Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1PADDING","SunJCE");
			Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1PADDING");
			cipher.init(Cipher.DECRYPT_MODE, pbk);

			byte[] btSrc =cipher.doFinal(Base64.decode(data));

			return new String(btSrc,ENCODING);

		} catch (Exception e) {
			logger.error(Strings.toString(e));
			return "";
		}
	}
	
	
	/**
	 * 获取文件的私钥
	 * @param keyPath
	 * @param passwd
	 * @return
	 * @throws Exception
	 */
	public static RSAPrivateKey getPrivateKey(String keyPath, String passwd) throws Exception {


		//Class<?> c = Class.forName("com.sun.net.ssl.internal.ssl.Provider");
		//Provider provider = (Provider)c.newInstance();
		//KeyStore ks = KeyStore.getInstance("PKCS12",provider);
		PrivateKey prikey = privateKeys.get(keyPath);
		if(prikey == null) {
			KeyStore ks = KeyStore.getInstance("PKCS12");
			FileInputStream fis = new FileInputStream(keyPath);

			char[] nPassword = null;
			if ((passwd == null) || passwd.trim().equals("")) {
				nPassword = null;
			} else {
				nPassword = passwd.toCharArray();
			}
			ks.load(fis, nPassword);
			fis.close();

			Enumeration<String> enumq = ks.aliases();
			String keyAlias = null;
			if (enumq.hasMoreElements()) {
				keyAlias = (String) enumq.nextElement();
			}

			prikey = (PrivateKey) ks.getKey(keyAlias, nPassword);
			
			privateKeys.put(keyPath, prikey);
		}

		return (RSAPrivateKey) prikey;
	}
}
